package servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dbutil.DBUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class RegisterServlet
 */
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
  		request.setCharacterEncoding("UTF-8");
        HttpSession httpSession=request.getSession();
        int Uid=0;
        String name = request.getParameter("Uname");
		String password = request.getParameter("password");
		String Umail = request.getParameter("Umail");
		JSONArray jsonarray = new JSONArray();
		JSONObject jsonobj = new JSONObject();
		
		DBUtil db=new DBUtil();
		Connection conn = db.getConn();
		try {
			String sql;
			sql="select * from User where name='"+name+"'";
			ResultSet rs = db.getResult(sql);
			if(rs.next()) {
				httpSession.setAttribute("error1","用户名重复");
				jsonobj.put("adreess","register");
				jsonarray.put(jsonobj);
				response.getWriter().println(jsonarray);
				response.sendRedirect("./PAGES/register.jsp");
				httpSession.setMaxInactiveInterval(10);
			}else {
				sql = "insert into User(id,name,password,email) values(?,?,?,?)";
				PreparedStatement ps = conn.prepareStatement(sql);
				ps.setInt(1, Uid);
				ps.setString(2, name);
				ps.setString(3, password);
				ps.setString(4, Umail);
				int result = ps.executeUpdate();
				if (result != 0) {
					System.out.println("注册成功");
					jsonobj.put("adreess","login");
					jsonarray.put(jsonobj);
					response.getWriter().println(jsonarray);
					response.sendRedirect("./PAGES/login.jsp");
				}else {
					response.getWriter().println("<script>alert(\"注册失败\");window.location.href=\"./ADMIN/Admin.jsp\"</script>");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(db!=null)
				db.release();//�ر�����
		} 
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
